package com.hlm.transparent.core.socketserver;

import com.hlm.transparent.core.handler.SocketInHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.springframework.beans.factory.annotation.Value;

/**
 * @program:transparent
 * @description:socket服务端
 * @author: xinY
 **/
public class SocketServer {
    @Value("${socket.server.port}")
    private int ip ;
    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup childGroup = new NioEventLoopGroup();

    public void start (){
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(childGroup,bossGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(ip)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        System.out.println("客户端连接"+channel.remoteAddress());
                        channel.pipeline().addLast(new ByteArrayEncoder());
                        channel.pipeline().addLast(new SocketInHandler());
                    }
                });
            ChannelFuture future= sb.bind().sync();
            future.channel().closeFuture().sync();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            try {
                childGroup.shutdownGracefully().sync();
                bossGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
